package net.phoenix.repository.value;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.jcr.Binary;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;

import net.phoenix.repository.InputStreamBinary;
import net.phoenix.repository.RepositoryRuntimeException;

/**
 * Jigsaw server
 * <p>
 * net.phoenix.repository.value
 * </p>
 * <p>
 * BinaryValue
 * </p>
 * 
 * @author <a href="shamphone@gmail.com">Li XiongFeng</a>
 * @date 2011-11-6
 * @version 1.0.0
 */
public class BinaryValue extends BasicValue {
	private Binary value;

	public BinaryValue(Binary value) {
		this.value = value;
	}
	/**
	 * @todo
	 * @param value
	 */
	public BinaryValue(String value) {
		this.value = new InputStreamBinary(value);
	}
	
	/**
	 * @todo
	 * @param value
	 */
	public BinaryValue(InputStream value) {
		this.value = new InputStreamBinary(value);
	}
	/**
	 * getType
	 * 
	 * @return int
	 */
	/*
	 * (non-Javadoc)
	 * 
	 * @see net.phoenix.repository.value.BasicValue#getType()
	 */
	@Override
	public int getType() {
		return PropertyType.BINARY;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.phoenix.repository.value.BasicValue#getStream()
	 */
	@Override
	public InputStream getStream() throws RepositoryException {
		return this.value.getStream();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.phoenix.repository.value.BasicValue#getBinary()
	 */
	@Override
	public Binary getBinary() throws RepositoryException {
		return this.value;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.phoenix.repository.value.BasicValue#getString()
	 */
	@Override
	public String getString() throws RepositoryException {
		InputStream is = null;
		try {
			is = value.getStream();
			Reader reader = new InputStreamReader(is, "UTF-8");
			StringBuilder builder = new StringBuilder();
			char[] buffer = new char[1024];
			int n = reader.read(buffer);
			while (n != -1) {
				builder.append(buffer, 0, n);
				n = reader.read(buffer);
			}
			return builder.toString();
		} catch (IOException ex) {
			throw new RepositoryException(ex);
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				throw new RepositoryException(e);
			}
		}
	}

	@Override
	public String toString() {
		try {
			return this.getString();
		} catch (RepositoryException e) {
			throw new RepositoryRuntimeException(e);
		}
	}

	@Override
	public int compareTo(Value o) {
		return (o.toString().compareTo(this.toString()));
	}

}
